﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons.Enums;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Chart;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 图表接口
    /// </summary>
    [Authorize]
    public class ChartController : BaseApiController
    {
        private static ILogger<ChartController> _logger;
        private readonly TokenHelper _tokenHelper;
        private readonly IChartLogic _chartLogic;

        public ChartController(
            ILogger<ChartController> logger,
            TokenHelper tokenHelper,
            IChartLogic chartLogic
        )
        {
            _logger = logger;
            _tokenHelper = tokenHelper;
            _chartLogic = chartLogic;
        }

        /// <summary>
        /// 费用提醒 已关阀
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> FYTX_YGF()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            var failResult = new BaseResult
            {
                errcode = 1,
                msg = "查询失败"
            };
            try
            {
                var chartDatas = await _chartLogic.FYTX_YGF(token.payload.areaid);
                var chartResult = new ChartResult
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(failResult);
            }
        }



        //小模块1
        [HttpGet]
        public IActionResult ChartTop1()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            var failResult = new BaseResult
            {
                errcode = 1,
                msg = "查询失败"
            };
            try
            {
                var chartDatas = _chartLogic.Top1(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(failResult);
            }
        }
        //小模块2
        [HttpGet]
        public IActionResult ChartTop2()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var obj = new object();
                using (var _context = ContextBuilder.Build())
                {
                    //排除库房的表
                    string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var district_ids = _context.District.Where(m => m.ProjectId == token.payload.areaid && !errorDistricts.Contains(m.Id)).Select(m => m.Id).ToArray();
                    var owners_ids = _context.Owner.Where(m => district_ids.Contains(m.DistrictId)).Select(m=>m.Id).ToArray();

                    var zrjs = _context.OrderDetail.Where(m => m.CreateTime >= DateTime.Now.Date && m.CostType == 1&& owners_ids.Contains(m.OwnerId)).Sum(m => m.Money).ToString("f2");
                    var zrjf = _context.OrderDetail.Where(m => m.CreateTime > DateTime.Now.AddDays(-1).Date && m.CreateTime < DateTime.Now.Date && m.CostType == 0 && owners_ids.Contains(m.OwnerId)).Sum(m => m.Money).ToString("f2");
                    var dyjf = _context.OrderDetail.Where(m => m.CreateTime.Year == DateTime.Now.Year && m.CreateTime.Month == DateTime.Now.Month && m.CostType == 0 && owners_ids.Contains(m.OwnerId)).Sum(m => m.Money).ToString("f2");
                    var bnjf = _context.OrderDetail.Where(m => m.CreateTime.Year == DateTime.Now.Year && m.CostType == 0 && owners_ids.Contains(m.OwnerId)).Sum(m => m.Money).ToString("f2");
                    obj = new
                    {
                        errcode = 0,
                        msg = "ok",
                        datas = new { zrjs, zrjf, dyjf, bnjf }
                    };
                    return Ok(obj);
                };
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult
                {
                    errcode = 1,
                    msg = "查询失败"
                });
            }
        }

        //小模块3_4
        [HttpGet]
        public IActionResult ChartTop3_4()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var chartDatas = _chartLogic.Top3_4(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult
                {
                    errcode = 1,
                    msg = "查询失败"
                });
            }
        }

        //各片区抄表情况 
        [HttpGet]
        public IActionResult ChartDistrictReadRatioData()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var chartDatas =  _chartLogic.GetDistrictReadRatioData();
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult
                {
                    errcode = 1,
                    msg = "查询失败"
                });
            }
        }
        //上季度用量
        [HttpGet]
        public IActionResult ChartLastSeasonDosage()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var chartDatas = _chartLogic.GetLastSeasonDosage(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult
                {
                    errcode = 1,
                    msg = "查询失败"
                });
            }
        }

        //上月用水量
        [HttpGet]
        public IActionResult ChartLastMonthDosage()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var chartDatas = _chartLogic.GetLastMonthDosage(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult
                {
                    errcode = 1,
                    msg = "查询失败"
                });
            }
        }
        //上年用量
        [HttpGet]
        public IActionResult ChartLastYearWaterDosage()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                var chartDatas =  _chartLogic.GetLastYearWaterDosage(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult { errcode = 1, msg = "查询失败" });
            }
        }
        //前三天用量
        [HttpGet]
        public IActionResult ChartFirstThreeDays()
        {
            var token = _tokenHelper.GetTokenByHttpContext();

            var failResult = new BaseResult
            {
                errcode = 1,
                msg = "查询失败"
            };
            try
            {
                var chartDatas = _chartLogic.GetFirstThreeDays(token.payload.areaid);
                var chartResult = new 
                {
                    errcode = 0,
                    msg = "ok",
                    datas = chartDatas
                };
                return Ok(chartResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(failResult);
            }
        }


        [HttpGet]
        public IActionResult GetMeterReadCount()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                using (var _context = ContextBuilder.Build())
                {

                    var SettlementDay10tepm = _context.SettlementDay.Where(m => m.ReadTime.Date > DateTime.Now.Date.AddDays(-11)).ToList();
                    var SettlementDay3= SettlementDay10tepm.Where(m => m.ReadTime.Date > DateTime.Now.Date.AddDays(-4)).GroupBy(m=>m.CtdeviceId).ToList();
                    var SettlementDay5 = SettlementDay10tepm.Where(m => m.ReadTime.Date > DateTime.Now.Date.AddDays(-6)).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDay7 = SettlementDay10tepm.Where(m => m.ReadTime.Date > DateTime.Now.Date.AddDays(-8)).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDay10 = SettlementDay10tepm.GroupBy(m => m.CtdeviceId).ToList();

                    string[] errorDistricts = { "77c2bf3d-48ea-4916-b0a2-5cab6d43c24c", "e7fd52a2-3ed0-425c-938e-26c34f397e44", "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var districtMeter = _context.Meter.Where(m=> !errorDistricts.Contains(m.DistrictId)).GroupBy(m => m.DistrictId);

                    var districts = _context.District.ToList();

                    var file = new List<object>();
                    foreach (var item in districtMeter)
                    {
                        var ctids = item.Select(m => m.CtdeviceId).ToArray();
                        var district = districts.FirstOrDefault(m => m.Id == item.Key);
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.districtName = district?.Name;
                        obj_temp.meterCount = ctids.Count();
                        obj_temp.day3 = SettlementDay3.Where(m=> ctids.Contains(m.Key)).Count();
                        obj_temp.day5 = SettlementDay5.Where(m => ctids.Contains(m.Key)).Count();
                        obj_temp.day7 = SettlementDay7.Where(m => ctids.Contains(m.Key)).Count();
                        obj_temp.day10 = SettlementDay10.Where(m => ctids.Contains(m.Key)).Count();

                        file.Add(obj_temp);
                    }
                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        [HttpGet]
        public IActionResult GetMeterReadCountEveryday()
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var SettlementDay5tepm = _context.SettlementDay.Where(m => m.ReadTime.Date > DateTime.Now.Date.AddDays(-5)).ToList();
                    var SettlementDay1 = SettlementDay5tepm.Where(m => m.ReadTime.Date == DateTime.Now.Date.AddDays(-1)).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDay2 = SettlementDay5tepm.Where(m => m.ReadTime.Date == DateTime.Now.Date.AddDays(-2)).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDay3 = SettlementDay5tepm.Where(m => m.ReadTime.Date == DateTime.Now.Date.AddDays(-3)).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDay4 = SettlementDay5tepm.Where(m => m.ReadTime.Date == DateTime.Now.Date.AddDays(-4)).GroupBy(m => m.CtdeviceId).ToList();

                    string[] errorDistricts = { "77c2bf3d-48ea-4916-b0a2-5cab6d43c24c", "e7fd52a2-3ed0-425c-938e-26c34f397e44", "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var districtMeter = _context.Meter.Where(m => !errorDistricts.Contains(m.DistrictId)).GroupBy(m => m.DistrictId);

                    var districts = _context.District.ToList();

                    var file = new List<object>();
                    foreach (var item in districtMeter)
                    {
                        var ctids = item.Select(m => m.CtdeviceId).ToArray();
                        var district = districts.FirstOrDefault(m => m.Id == item.Key);
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.districtName = district?.Name;
                        obj_temp.meterCount = ctids.Count();
                        obj_temp.day1 = SettlementDay1.Where(m => ctids.Contains(m.Key)).Count();
                        obj_temp.day2 = SettlementDay2.Where(m => ctids.Contains(m.Key)).Count();
                        obj_temp.day3 = SettlementDay3.Where(m => ctids.Contains(m.Key)).Count();
                        obj_temp.day4 = SettlementDay4.Where(m => ctids.Contains(m.Key)).Count();

                        file.Add(obj_temp);
                    }
                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }
    }
}